package api

import (
	"api_gateway/basic/config"
	chat "api_gateway/basic/proto/chat"
	"api_gateway/untils"
	"context"
	"encoding/json"
	"github.com/streadway/amqp"
	"log"
	"time"
)

func PushPrivateToUser() {
	// 初始化rabbitmq连接
	rabbitmq := untils.NewRabbitMQSimple(config.PRIVATE_CHAT)
	// 从队列中获取消息
	private, err := rabbitmq.ConsumeSimple()
	if err != nil {
		log.Printf("获取队列消息失败: %v", err)
		return
	}
	log.Printf(" [*] 讯息推送服务启动，等待消息...")

	// 处理消息
	forever := make(chan bool)
	//启用协程处理消息
	go func() {
		for d := range private {
			// 异步处理每条消息
			go processPrivateMessage(d, rabbitmq)
		}
	}()

	<-forever
}

// 处理私聊消息
func processPrivateMessage(d amqp.Delivery, rabbitmq *untils.RabbitMQ) {
	// 记录接收到的消息
	log.Printf("接收到消息:%s", string(d.Body))

	// 解析消息为SendMessageReq结构体
	var privateMessage chat.SendMessageReq
	if err := json.Unmarshal(d.Body, &privateMessage); err != nil {
		log.Printf("解析消息失败: %v, 消息内容: %s", err, d.Body)
		return
	}

	// 设置调用服务端的超时上下文
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// 调用服务端保存消息
	response, err := config.ChatClient.SendMessage(ctx, &privateMessage)
	if err != nil {
		log.Printf("调用通讯服务失败: %v, 消息ID: %d->%d", err,
			privateMessage.FormUserId, privateMessage.ToTargetId)
		return
	}
	// 处理成功
	log.Printf("消息保存成功: 消息ID=%s, 发送者=%d, 接收者=%d",
		response.MessageId, privateMessage.FormUserId, privateMessage.ToTargetId)
}
